package com.example.weather.city_manager

import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.AdapterView.OnItemClickListener
import android.widget.ImageView
import android.widget.ListView
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.example.weather.R
import com.example.weather.data.CityDao
import com.example.weather.data.WeatherDatabase
import java.util.ArrayList

/**
 * @author Y7993
 */
// 删除城市活动类，负责城市的删除操作
class DeleteCityActivity : AppCompatActivity(), View.OnClickListener {
    var errorIv: ImageView? = null
    var rightIv: ImageView? = null
    var deleteLv: ListView? = null

    //列表数据源
    var mDatas: MutableList<String?> = ArrayList<String?>()
    var deleteCitys: MutableList<String?> = ArrayList<String?>()
    private var cityDao: CityDao? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_delete_city)
        //找到组件
        deleteLv = findViewById<ListView>(R.id.delete_lv)
        errorIv = findViewById<ImageView>(R.id.delete_iv_error)
        rightIv = findViewById<ImageView>(R.id.delete_iv_right)

        //获取数据
        val weatherDatabase = WeatherDatabase.getDatabase(this)
        cityDao = weatherDatabase.getCityDao()
        mDatas = getData()

        //设置监听事件
        errorIv!!.setOnClickListener(this)
        rightIv!!.setOnClickListener(this)
        //设置适配器
        val baseAdapter = DeleteCityAdapter(this, mDatas)
        deleteLv!!.adapter = baseAdapter
        //设置点击事件的监听事件
        deleteLv!!.onItemClickListener =
            OnItemClickListener { adapterView: AdapterView<*>?, view: View?, pos: Int, id: Long ->
                val deletecity = view!!.findViewById<TextView>(R.id.item_delete_tv) //找到点击的textview
                val cityname = deletecity.text.toString().trim { it <= ' ' }  //城市名
                mDatas.remove(cityname)
                deleteCitys.add(cityname)
                baseAdapter.notifyDataSetChanged()
            }
    }

    // 获取所有城市数据
    private fun getData(): MutableList<String?> {
        val cityList: MutableList<String?> = ArrayList<String?>()
        val cities = cityDao!!.findAll()
        if (cities != null) {
            for (c in cities) {
                c?.let { cityList.add(it.getName()) }
            }
        }
        return cityList
    }

    // 取消删除操作，返回城市管理活动
    fun cancel() {
        val intent_add = Intent(this, CityManagerActivity::class.java)
        startActivity(intent_add)
    }

    // 确认删除选中的城市
    fun ok() {
        for (s in deleteCitys) {
            cityDao!!.deleteByName(s)
        }
        finish()
    }

    override fun onClick(view: View) {
        if (view.id == R.id.delete_iv_error) {
            cancel()
        } else if (view.id == R.id.delete_iv_right) {
            ok()
        }
    }
}
